package com.bestom.bestoma10demo;

import java.io.IOException;

public class NetworkStateListener {
    private Boolean mIsOnline = null;
    private boolean isEnd = false;
    private Thread mListenerThread;

    public NetworkStateListener(NetworkStateChangedListener listener) {
        mListener = listener;
        start();
    }

    public interface NetworkStateChangedListener {
        void change(boolean onOff);
    }

    private NetworkStateChangedListener mListener;

    public void setNetworkStateChangedListener(NetworkStateChangedListener listener) {
        this.mListener = listener;
    }

    public Boolean getCurrentNetworkState() {
        return mIsOnline;
    }

    public void release() {
        isEnd = true;
        mListenerThread.interrupt();
    }

    private void start() {
        mListenerThread = new Thread() {
            @Override
            public void run() {
                while (!isEnd) {
                    boolean isOnline = isOnline();

                    if (mIsOnline != null && mIsOnline != isOnline) {
                        //The connection state has changed
                        if (mListener != null) {
                            mListener.change(isOnline);
                        }
                    }else if (mIsOnline == null){
                        if (mListener != null) {
                            mListener.change(isOnline);
                        }
                    }
                    mIsOnline = isOnline;

                    try {
                        Thread.sleep(1000 * 5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        isEnd = true;
                    }
                }
            }
        };
        mListenerThread.start();
    }

    public static String ipServer;

    private boolean isOnline() {
        Runtime runtime = Runtime.getRuntime();
        try {
            Process ipProcess = runtime.exec("ping -c 3 " + ipServer);
            int exitValue = ipProcess.waitFor();
            return (exitValue == 0);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }
}
